//--------------------------------------------------------//
//Filename:app.js
//Create Time:2020年02月06日 星期四 22时53分05秒
//Description: 入口文件 app
//------------------------------------------------------- //

const Koa=require('koa');
const path=require('path');
const KoaBody = require('koa-body');
const cors = require('koa2-cors');
const koastatic = require('koa-static');
const app = new Koa();
const jwt = require('koa-jwt');
const error = require('koa-json-error');
const parameter = require('koa-parameter');
const config = require('./config');
require('colors');

//log4js 日志
const logger = require('./log/weblog');

//数据库连接
require('./db/db');

//静态目录
app.use(koastatic(path.join(__dirname,'public')));

//上传目录
app.use(KoaBody({
	multipart:true,
	formidable:{
		uploadDir:path.join(__dirname,'public/uploads'),
		hash:'md5',
		keepExtensions:true,
		onFileBegin:(name,file)=>{
			let  sourepath = path.join(__dirname,`public/uploads/${file.name}`);
			file.path= sourcepath;
		}
	}
}));

//错误处理页面
app.use(error({
	postFormat:(e,{stack,...rest})=>app.env ==='production'?rest:{stack,...rest}
}));

//跨域
app.use(cors({
	origin:function(ctx){
		return '*';
	}
}));

//参数校验
app.use(parameter(app));

//Token 
const secret =config.SECRETKEY; 
const tokenExpiresTime = 1000 * 60 * 60 * 24;
app.use(jwt({secret:secret}).unless({
  path:[
	 /^\/login/,
	 /^\/trylogin/,
	 /^\/upload/,
	 /^\/checktoken/,
	 /^\/api\/[/\w]+/
	 ]
}));

//路由
const routerfunc = require('./router/routers');
routerfunc(app);

//app.env = 'production';
//process.env.NODE_ENV = 'production';
app.listen(3000);
console.log(`app env:${app.env}`.green);


